(function($) {
	var UnblestImage = function(){
		
	}
	UnblestImage.prototype.make = function(widget, depth){
		var self = this
		if(!depth){ depth = 0 }
		if(depth>=5) { return }
		var txt = widget.text()
		var words = txt.match(/([\u0430-\u044f\u0410-\u042fa-zA-Z]+)/gi)
		var len = words.length
		var phLen = Math.random()*3+1
		var offset = parseInt(Math.random()*(len-phLen))
		var phrase = words.slice(offset, offset+phLen).join(' ')
		this.query(phrase, function(img){
			var A = $('<a />')
				.attr({'href':img.url, target:'blank'})
				.addClass('unblest-image-a')
			var IMG = $('<img />')
				.attr({'src':img.thumbnail_url, align:'left'})
				.addClass('unblest-image-img')
				.appendTo(A)
			widget.prepend(A)
		},
		function(){
			self.make(widget, ++depth)
		})
	}
	UnblestImage.prototype.query = function(keywords, cb, err) {
		var query = 'select * from search.images where query="'+keywords+'" and mimetype like "%jpeg%"'
		$.get('http://query.yahooapis.com/v1/public/yql',
			{q:query, format:'json'},function(data){
				if(!data.query.results) {
					err()
					return
				}
				var img
				for(i in data.query.results.result) {
					img = data.query.results.result[i]
					if(Math.random>1/(Math.sqrt(Math.PI))) {break}// Yes, I am *CRAZY*
				}
				
				cb(img)
			},'json')
	}

	$.fn.unblestImage = function(){
		var element = this
		var unbImg = new UnblestImage
		element.each(function(k,v){
			unbImg.make($(v))
		})
	}
})(jQuery)
